package com.project.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.project.entity.Message;
import com.project.entity.Project;
import com.project.entity.User;
import com.project.util.DBHelp;
import com.project.util.RowMapper;

public class MessageDao {
	DBHelp<Message> dbHelp=new DBHelp<Message>();
	public void save(Message ms) {
		String sql="insert into t_message(id,cont,createtime,userid,projectid) values(?,?,?,?,?)";
		dbHelp.executeSQL(sql, ms.getId(),ms.getCont(),ms.getCreatetime(),ms.getUserid(),ms.getProjectid());
		
	}
	public List<Message> findAllMessageByProjectid(String pid) {
		StringBuffer sql=new StringBuffer();
		sql.append("SELECT t_message.id,t_message.cont,t_message.createtime,t_message.userid,    ");
		sql.append(" t_message.projectid,t_user.username AS username,t_user.id AS userid, t_project.id AS projectid,t_project.name FROM t_message   ");
		
		sql.append("LEFT JOIN t_user ON t_user.id=t_message.userid  ");
		sql.append("LEFT JOIN t_project ON t_project.id=t_message.projectid ");
		sql.append("WHERE t_message.projectid=? order by t_message.createtime desc ");
		return dbHelp.executeQueryForList(sql.toString(), new messageRowMapper(), pid);
	}

	private class messageRowMapper implements RowMapper<Message>{

		public  Message mapRow(ResultSet rs) throws SQLException {
			Message m=new Message();
			
			User user=new User();
			user.setUsername(rs.getString("username"));
			user.setId(rs.getString("userid"));
			
			Project p=new Project();
			p.setId(rs.getString("projectid"));
			p.setName(rs.getString("name"));
			
			
			m.setCont(rs.getString("cont"));
			m.setCreatetime(rs.getString("createtime"));
			m.setId(rs.getString("id"));
			m.setProjectid(rs.getString("projectid"));
			m.setUserid(rs.getString("userid"));
			
			
			
			m.setUser(user);
			m.setProject(p);
			
			
			return m;
	
		}
		
	}
	
}
